<template>
  <!-- 代码编辑器 -->
  <div ref="editorContainer" class="editor-container"></div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref, watch, defineProps, defineEmits } from 'vue';
import * as monaco from 'monaco-editor';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker';
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker';
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';
import { language as pythonLanguage } from 'monaco-editor/esm/vs/basic-languages/python/python.js';
//props
const props = defineProps({modelValue: String,});

const emit = defineEmits(['update:modelValue']);
const editorContainer = ref(null);
let editor = null;

// 配置monaco环境
self.MonacoEnvironment = {
  getWorker(_, label) {
    if (label === 'json') {
      return new jsonWorker();
    }
    if (label === 'css' || label === 'scss' || label === 'less') {
      return new cssWorker();
    }
    if (label === 'html' || label === 'handlebars' || label === 'razor') {
      return new htmlWorker();
    }
    if (label === 'typescript' || label === 'javascript') {
      return new tsWorker();
    }
    return new editorWorker();
  },
};

// 初始化编辑器
const initEditor = () => {
  editor = monaco.editor.create(editorContainer.value, {
    value: props.modelValue,
    language: 'python',
    theme: 'vs', // 可根据需要修改主题
  });

  // 监听编辑器内容变化
editor.onDidChangeModelContent(() => {
    const value = editor.getValue();
    emit('update:modelValue', value);
  });
};

// 注册Python代码补全
monaco.languages.registerCompletionItemProvider('python', {
      provideCompletionItems: function () {
        let suggestions = [];
        pythonLanguage.keywords.forEach((item) => {
          suggestions.push({
            label: item,
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: item,
          });
        });
        // 可以继续添加其他类型的自动补全建议，如函数、变量等
        return { suggestions: suggestions };
      },
});

onMounted(() => {
  //初始化
  initEditor();
});

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose();
  }
});

watch(
  () => props.modelValue,
  (newValue) => {
    if (editor) {
      const currentValue = editor.getValue();
      if (newValue !== currentValue) {
        editor.setValue(newValue);
      }
    }
  }
);
</script>

<style scoped>
.editor-container {
  min-width: 800px;
  height: 300px; /* 可根据需要调整高度 */
  padding: 10px;
  border-radius: 10px;
  border: 2px rgba(209, 199, 199, 0.6) dotted;

  /* overflow: hidden; */
}
</style>